package com.oocl.o2o.merchant.service.impl;


import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.oocl.o2o.connectutil.dto.MStatusFeedBackDTO;
import com.oocl.o2o.connectutil.dto.MerchantDTO;
import com.oocl.o2o.connectutil.util.RegisterStatusUtil;
import com.oocl.o2o.merchant.dao.MerchantDao;
import com.oocl.o2o.merchant.entity.Merchant;
import com.oocl.o2o.merchant.service.MerchantManager;
import com.oocl.o2o.merchant.vo.AuditInfo;

@Service
public class MerchantManagerImpl implements MerchantManager {
	@Autowired
	private MerchantDao merchantDao;

	@Transactional
	@Override
	public Merchant login(String username, String password) {
		Merchant merchant = merchantDao.findByUsernameAndPassword(username, password);
		return merchant;
	}

	@Transactional
	@Override
	public Merchant register(Merchant merchant,byte[] idCardByte,byte[] portraitByte) {
		merchant = merchantDao.add(merchant);
		if(merchant==null){
			return null;
		}
		sendAuditToA(merchant, idCardByte, portraitByte);
		return merchant;
	}

	@Transactional
	@Override
	public Merchant reAudit(String merchantId, String address, String idCard, String portrait, byte[] idCardByte,
			byte[] portraitByte) {
		Merchant merchant = merchantDao.findById(merchantId);
		if(merchant ==null)
			return null;
		merchant.setAddress(address);
		merchant.setIdCard(idCard);
		merchant.setPortrait(portrait);
		if(!sendAuditToA(merchant, idCardByte, portraitByte)) {
			return null;
		}
		return merchant;
	}

	private boolean sendAuditToA(Merchant merchant, byte[] idCardByte, byte[] portraitByte) {
		Base64 base64 = new Base64();
		String uname = merchant.getUsername();
		String address =merchant.getAddress();
		String idCard = base64.encodeAsString(idCardByte);
		String portrait = base64.encodeAsString(portraitByte);
		int status = 0;
		String content = null;
		MerchantDTO merchantDTO = new MerchantDTO(uname, address, idCard, portrait, status, content);
		RegisterStatusUtil.send(merchantDTO);
		return true;
	}
	
	@Override
	public AuditInfo getAuditInfo(String username) {
		MStatusFeedBackDTO merchantDTO;
		try {
			merchantDTO = RegisterStatusUtil.receive(username);
		} catch (NullPointerException e) {
			e.printStackTrace();
			return null;
		}
		if(merchantDTO ==null)
			return null;
		int status = merchantDTO.getStatus();
		String content = merchantDTO.getContent();
		return new AuditInfo(username, status, content);
	}
	
	@Override
	public Merchant getMerchant(String id) {
		Merchant merchant = merchantDao.findById(id);
		return merchant;
	}
	@Override
	public Merchant getMerchantByUsername(String username) {
		return merchantDao.findByUsername(username);
	}
}
